<template>
  <div class="container">
    <div class="search">
      <el-form :inline="true" :model="searchForm" class="demo-form-inline" ref="ruleForm">
        <el-form-item label="姓名" prop="student_name">
          <el-input v-model="searchForm.student_name" placeholder="学生姓名"></el-input>
        </el-form-item>
        <el-form-item label="班级" prop="clazz">
          <el-input v-model="searchForm.clazz" placeholder="班级"></el-input>
        </el-form-item>
        <el-form-item label="课程" prop="course">
          <el-input v-model="searchForm.course" placeholder="课程"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit">查询</el-button>
          <el-button type="primary" @click="exportExcel">导出</el-button>
          <el-button type="primary" @click="resetForm('ruleForm')">重置</el-button>

        </el-form-item>
      </el-form>
    </div>
    <div class="header">
      <el-button type="primary" plain size="small" @click="showAddForm">新增</el-button>
      <el-button type="danger" plain size="small" @click="uploadDialogFormVisible=true">导入</el-button>
    </div>
    <div class="table">
      <el-table
        :data="tableData"
        style="width: 100%">
        <el-table-column
          prop="student_name"
          label="姓名">
        </el-table-column>
        <el-table-column
          prop="student_no"
          label="学号">
        </el-table-column>
        <el-table-column
          prop="student_age"
          label="年龄">
        </el-table-column>
        <el-table-column
          prop="student_gender"
          label="性别">
        </el-table-column>
        <el-table-column
          prop="clazz"
          label="班级">
        </el-table-column>
        <el-table-column
          prop="course"
          label="课程">
        </el-table-column>
        <el-table-column
          prop="school_time"
          label="入学时间">
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button
              size="mini"
              @click="handleEdit(scope.$index, scope.row)">编辑
            </el-button>
            <el-button
              size="mini"
              type="danger"
              @click="handleDelete(scope.$index, scope.row)">删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="paginator">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[5,10, 20, 30, 40]"
        :page-size=size
        layout="total, sizes, prev, pager, next, jumper"
        :total=total>
      </el-pagination>
    </div>
    <!--    弹窗-->
    <div>
      <el-dialog :title="title" :visible.sync="dialogFormVisible" @close="clearInfo">
        <el-form :model="form" :rules="rules" ref="formData">
          <el-form-item label="姓名" :label-width="formLabelWidth" prop="student_name">
            <el-input v-model="form.student_name" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="学号" :label-width="formLabelWidth" prop="student_no">
            <el-input v-model="form.student_no" autocomplete="off"></el-input>
          </el-form-item>

          <el-form-item label="性别" :label-width="formLabelWidth" prop="student_gender">
            <el-select v-model="form.student_gender" placeholder="请选择" style="width: 100%">
              <el-option label="男" :value="1"></el-option>
              <el-option label="女" :value="2"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="入学时间" :label-width="formLabelWidth" prop="school_time">
            <el-date-picker v-model="form.school_time" type="date" placeholder="选择入学时间"
                            style="width: 100%"></el-date-picker>
          </el-form-item>
          <el-form-item label="年龄" :label-width="formLabelWidth" prop="student_age">
            <el-input v-model="form.student_age" autocomplete="off"></el-input>
          </el-form-item>

          <el-form-item label="班级" :label-width="formLabelWidth" prop="clazz_id">
            <el-select v-model="form.clazz_id" placeholder="请选择" style="width: 100%">
              <el-option
                v-for="clazz in clazzs"
                :key="clazz.id"
                :label="clazz.name"
                :value="clazz.id">
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="课程" :label-width="formLabelWidth" prop="course_id">
            <el-select v-model="form.course_id" placeholder="请选择" style="width: 100%">
              <el-option
                v-for="course in courses"
                :key="course.id"
                :label="course.course_name"
                :disabled=course.disabled
                :value="course.id">
              </el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitForm">确 定</el-button>
        </div>
      </el-dialog>

    </div>
    <div class="upload">
      <el-dialog title="导入数据" :visible.sync="uploadDialogFormVisible" @close="clearInfo" width="30%">
        <!--
        action:文件上传的后台接口
        -->
        <el-upload
          class="upload-demo"
          drag
          :on-success="uploadSuccess"
          :on-error="uploadError"
          :action="uploadServer">
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
          <div class="el-upload__tip" slot="tip">只能上传excel文件，且不超过500kb</div>
        </el-upload>
      </el-dialog>

    </div>
  </div>
</template>

<script>
import {uploadServer} from '@/settings'
import {student_insert_edit, studentDelete, studentOne, studentPage} from "@/api/student";
import {clazzList} from "@/api/clazz";
import {courseList} from "@/api/course";
import saveAs from 'file-saver'

export default {
  name: 'index',
  data() {
    return {
      uploadServer: uploadServer + '/students/import',
      multipleSelection: [],
      roles: [],
      depts: [],
      title: '新增',
      dialogFormVisible: false,
      uploadDialogFormVisible: false,
      formLabelWidth: "80px",
      currentPage: 1,
      size: 5,
      total: 0,
      tableData: [],
      searchForm: {
        'student_name': "",
        "clazz": "",
        "course": "",
      },
      form: {
        'student_no': "",
        'student_name': "",
        "student_age": "",
        "student_gender": "",
        "clazz_id": "",
        "course_id": ""
      },
      rules: {
        student_no: [
          {required: true, message: '请输入学号', trigger: 'blur'},
        ],
        student_name: [
          {required: true, message: '请输入姓名', trigger: 'blur'}
        ],
        student_gender: [
          {required: true, message: '请选择性别', trigger: 'blur'}
        ],
        student_age: [
          {required: true, message: '请输入年龄', trigger: 'blur'}
        ],
        school_time: [
          {required: true, message: '请选择入学时间', trigger: 'blur'}
        ],
        clazz_id: [
          {required: true, message: '请选择班级', trigger: 'blur'}
        ],
        course_id: [
          {required: true, message: '请选择课程', trigger: 'blur'}
        ]
      },
      courses: [],
      clazzs: []
    }
  },
  methods: {
    uploadSuccess(response) {
      if (response.code==20000){
        this.$notify.success(response.message)
      }else{
        this.$notify.error(response.message)
      }
      this.uploadDialogFormVisible = false
      this.tableDataPage()
    },
    uploadError(err) {
      this.$notify.error('数据导入失败')
    },
    async exportExcel() {
      // 发送异步请求导出数据
      const response = await fetch(uploadServer + '/students/export?student_name='
        + this.searchForm.student_name + "&clazz="
        + this.searchForm.clazz + "&course="
        + this.searchForm.course)
      // 获取响应的excel的二进制数据
      const blob = await response.blob()
      // 如何将二进制数据保存为 .excel文件  file-saver
      saveAs(blob,"students.xlsx")
    },
    // 重置 搜索表单数据
    resetForm(formName) {
      this.$refs[formName].resetFields();
      this.currentPage = 1
      this.tableDataPage()
    },
    // 搜索
    onSubmit() {
      this.currentPage = 1
      this.tableDataPage()
    },

    showAddForm() {
      //获取班级列表数据
      clazzList().then(response => {
        this.clazzs = response.clazzs
      })
      // 获取课程列表数据
      courseList().then(response => {
        let courses = response.courses.map(course => {
          if (course.course_state == 0) {
            course.disabled = true
          } else {
            course.disabled = false
          }
          return course
        })
        this.courses = courses
      })
      this.dialogFormVisible = true
    },
    clearInfo() {
      this.form = {
        'student_no': "",
        'student_name': "",
        "student_age": "",
        "student_gender": "",
        "clazz_id": "",
        "course_id": ""
      }
      // 清空校验规则
      this.$refs.formData.clearValidate()
      this.title = "新增"
    },
    submitForm() {
      this.$refs.formData.validate(val => {
        if (val) {
          student_insert_edit(this.form).then(response => {
            this.$notify.success(response.message)
            this.dialogFormVisible = false
            this.tableDataPage()
          })
        } else {
          this.$notify.warning('请填写完整的表单数据')
        }
      })
    },
    handleSizeChange(val) {
      this.size = val
      this.tableDataPage()
    },
    handleCurrentChange(val) {
      this.currentPage = val
      this.tableDataPage()
    },
    handleEdit(index, row) {
      //获取班级列表数据
      clazzList().then(response => {
        this.clazzs = response.clazzs
      })
      // 获取课程列表数据
      courseList().then(response => {
        this.courses = response.courses
      })
      this.title = '编辑'
      this.dialogFormVisible = true
      // 发送异步请求 获取学生详细信息
      studentOne(row.id).then(response => {
        this.form = response.student
      })
    },
    handleDelete(index, row) {
      this.$confirm('此操作将永久删除数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 发送异步请求删除数据
        studentDelete(row.id).then(response => {
          this.$notify.success(response.message)
          this.tableDataPage()
        })
      }).catch(() => {
        this.$notify({
          type: 'info',
          message: '已取消删除'
        });
      });

    },
    tableDataPage() {
      studentPage({
        page: this.currentPage,
        size: this.size,
        clazz: this.searchForm.clazz,
        course: this.searchForm.course,
        student_name: this.searchForm.student_name
      }).then(response => {
        this.total = response.total
        this.tableData = response.table_data
      })
    }
  },
  created() {
    this.tableDataPage()
  }
}
</script>


<style scoped lang="scss">
.container {
  padding: 20px;
  box-sizing: border-box;
}

.header {
  margin-top: 20px;
  margin-bottom: 20px;
}

.paginator {
  margin-top: 15px;
}

.search {
  border-bottom: 1px solid #cccccc;
  margin-top: 10px;
}
</style>



